package controller

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
	strconv "strconv"
	"ylb/interceptor"
	"ylb/service"
	"ylb/service/impl"
	"ylb/tool"
	"ylb/vo"
)

type JobController struct {
	service service.JobService
}

func NewJobController(gin *gin.Engine) JobController {
	controller := JobController{}
	controller.service = impl.NewJobServiceImpl()
	controller.JobRoute(gin)
	return controller
}
func GetUserId(ctx *gin.Context) uint {

	id := sessions.Default(ctx).Get("userId")

	userId := fmt.Sprintf("%v", id)
	atoi, err := strconv.Atoi(userId)
	if err != nil {
		fmt.Println("method-【GetUserId】 Session GetUserId Error...")
		ctx.JSON(http.StatusOK, tool.Error("查询失败", gin.H{

			"cause": "token错误",
		}))

		ctx.Abort()
		return 0

	}
	return uint(atoi)
}

func (jobController JobController) JobRoute(ginServer *gin.Engine) {
	group := ginServer.Group("/job")
	{

		store := cookie.NewStore([]byte("secret3652"))
		group.Use(sessions.Sessions("jobSession", store))
		//token拦截器，全局作用
		group.Use(interceptor.TokenInterceptor())
		//查询所有
		group.GET("/all", jobController.selectAll)
		//查询所有已收藏
		group.GET("/all/collect", jobController.selectByCollect)
		//收藏/取消收藏 任务
		group.GET("/collect/:jobId/:collect", jobController.collectJob)
		//查询某个分类的所有
		group.GET("/all/:classify", jobController.selectByClassify)
		//查询某个日期之前所有
		group.GET("/all/day/:day", jobController.selectByLimitDay)
		//提交之前检查是否提交过
		group.POST("/add", interceptor.RepeatJobPost(), jobController.insert)
		//删除
		group.GET("/del/:jobId", jobController.delete)
		//根据天、时、分、秒查找 未过期/已过期 任务
		group.POST("/all/where", jobController.selectByWhere)
		group.POST("/all/search", jobController.selectByLike)
	}

}

//---------------------------------------------------------------------------------------------
func (jobController JobController) selectByLimitDay(ctx *gin.Context) {
	userId := GetUserId(ctx)

	//获取增长天数
	dayStr := ctx.Param("day")
	atoi, err := strconv.Atoi(dayStr)
	if err != nil {
		fmt.Println(err)
		return

	}
	all := jobController.service.SelectAllByDayExpire(userId, atoi)
	ctx.JSON(http.StatusOK, tool.Success("查询成功", gin.H{
		"jobList": all,
		"size":    len(all),
	}))
}
func (jobController JobController) selectByCollect(ctx *gin.Context) {
	userId := GetUserId(ctx)

	all := jobController.service.SelectAllByCollect(uint(userId))
	ctx.JSON(http.StatusOK, tool.Success("查询成功", gin.H{
		"jobList": all,
		"size":    len(all),
	}))
}

func (jobController JobController) selectAll(ctx *gin.Context) {

	userId := GetUserId(ctx)

	all := jobController.service.SelectAll(userId)

	ctx.JSON(http.StatusOK, tool.Success("查询成功", gin.H{
		"jobList": all,
		"size":    len(all),
	}))
}
func (jobController JobController) selectByClassify(ctx *gin.Context) {
	userId := GetUserId(ctx)

	classify := ctx.Param("classify")
	cify, err := strconv.Atoi(classify)

	if err != nil {
		ctx.JSON(http.StatusOK, tool.Error("查询失败", gin.H{
			"cause": "参数非法",
		}))
		return
	}
	byClassify := jobController.service.SelectAllByClassify(uint(userId), uint(cify))

	ctx.JSON(http.StatusOK, tool.Success("查询成功", gin.H{
		"jobList": byClassify,
		"size":    len(byClassify),
	}))
}
func (jobController JobController) collectJob(ctx *gin.Context) {
	param1 := ctx.Param("jobId")
	param2 := ctx.Param("collect")
	jobId, err := strconv.Atoi(param1)
	collect, err := strconv.Atoi(param2)
	if param1 == "" || param2 == "" || err != nil {
		ctx.JSON(http.StatusOK, tool.Error("查询失败", gin.H{
			"cause": "参数非法",
		}))
		return
	}

	job := jobController.service.CollectJob(jobId, collect != 1)
	if job != 1 {
		ctx.JSON(http.StatusOK, tool.Error("收藏失败", nil))
	} else {
		ctx.JSON(http.StatusOK, tool.Success("收藏成功", nil))
	}

}
func (jobController JobController) insert(ctx *gin.Context) {

	userId := GetUserId(ctx)
	//拦截器消耗了vo,此处只能从context取
	value, exists := ctx.Get("jobInsertVo")
	insertVo := value.(vo.JobInsertVo)
	insertVo.UserId = userId

	if !exists {
		ctx.JSON(http.StatusOK, tool.Error("添加失败", gin.H{
			"cause": "job非法",
		}))
		return
	}

	insert := jobController.service.Insert(insertVo.ParseJob())
	if insert != 1 {
		ctx.JSON(http.StatusOK, tool.Error("添加失败", nil))
	} else {
		ctx.JSON(http.StatusOK, tool.Success("添加成功", gin.H{}))
	}
}
func (jobController JobController) delete(ctx *gin.Context) {

	id := ctx.Param("jobId")

	jobId, err := strconv.Atoi(id)
	if err != nil {
		fmt.Println(err)
		ctx.JSON(500, tool.Error("删除失败", nil))
	}
	delete := jobController.service.Delete(uint(jobId))
	if delete != 1 {
		ctx.JSON(http.StatusOK, tool.Error("删除失败", nil))
	} else {
		ctx.JSON(http.StatusOK, tool.Success("删除成功", nil))
	}
}

//筛选查询
func (jobController JobController) selectByWhere(ctx *gin.Context) {

	userId := GetUserId(ctx)

	m := map[string]int{}
	err := ctx.BindJSON(&m)
	if err != nil {
		ctx.JSON(http.StatusOK, tool.Error("查询失败", nil))
		return
	}
	where := jobController.service.SelectAllByWhere(userId, m)

	ctx.JSON(http.StatusOK, tool.Success("查询成功", gin.H{
		"jobList": where,
		"size":    len(where),
	}))

}

func (jobController JobController) selectByLike(ctx *gin.Context) {

	m := map[string]string{}
	err := ctx.BindJSON(&m)
	if err != nil {
		ctx.JSON(http.StatusOK, tool.Error("查询失败", nil))
		return
	}
	like := m["search"]
	byLike := jobController.service.SelectAllByLike(like)
	ctx.JSON(http.StatusOK, tool.Success("查询成功", gin.H{
		"jobList": byLike,
		"size":    len(byLike),
	}))

}
